<template>
    <div class="imm">
        <!-- :on-change="uploadFile" -->
        <el-upload :limit="limit" accept="image/jpeg, image/png, image/jpg" :on-change="uploadFile" list-type="picture-card"
            :multiple="multiple" :auto-upload="false" :file-list="fileList" :on-exceed="handleExceed" :action="'#'"
            :on-preview="handlePictureCardPreview" :on-remove="handleRemove" class="avatar-uploader" ref="upload"
            :class="{ hide: showUpload }" :disabled="disabled"
            :style="isHit ? { border: '1px dashed red', borderRadius: '5px', boxSizing: 'border-box' } : {}">
            <div style="display: flex;flex-direction: column;align-items: center;justify-content: center;">
                <el-icon>
                    <Plus />
                </el-icon>
                <div style="font-size: 12px;color: gray;">{{ hit }}</div>
            </div>
        </el-upload>

        <el-dialog v-model="dialogVisible">
            <el-image style="width: 100%; height: 100%" :src="imgUrl.url" :initial-index="1" fit="cover"
                :preview-src-list="[item]" />
        </el-dialog>
    </div>
</template>

<script>
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios';
let config = require('../../config.js')
export default {
    emits: ['returnData', 'delUrl'],
    components: {
        Plus: Plus
    },
    props: {
        limit: Number,
        fileList: {
            default: []
        },
        multiple: Boolean,
        hit: String,
        disabled: Boolean,
        isMust: Boolean
    },
    data() {
        return {
            showUpload: false, //控制limit最大值之后 关闭上传按钮
            dialogVisible: false, //查看图片弹出框
            imgUrl: [], //上传图片后地址合集
            AllFile: JSON.parse(JSON.stringify(this.fileList)),
            isHit: false
        };
    },
    //监听上传图片的数组(为了处理修改时,自动渲染问题,和上传按钮消失问题);
    watch: {
        fileList() {
            if (this.fileList.length == this.limit) this.showUpload = true;
            else this.showUpload = false;
            this.AllFile = JSON.parse(JSON.stringify(this.fileList))
        },
        AllFile() {
            if (this.limit == 1 && this.isMust) {
                this.isHit = false
            }
        }
    },
    mounted() {
        if (this.fileList.length == this.limit) this.showUpload = true;
        else this.showUpload = false;
    },

    methods: {
        //文件列表移除文件时的函数
        handleRemove(file, fileList) {
            const index = this.fileList.findIndex((item) => item === file.uid);

            if (index >= 0) {
                this.$emit("delUrl", this.imgUrl[index]);
            } else {
                //返回图片的索引位置
                const missingIndex = this.AllFile.findIndex(element => element.url === file.url);
                this.$emit("delUrl", missingIndex);
            }
            this.AllFile = this.AllFile.filter(element => element.url !== file.url);
            this.imgUrl.splice(index, 1);
            if (fileList.length < this.limit) this.showUpload = false;
        },

        //点击文件列表中已上传的文件时的函数
        handlePictureCardPreview(file) {
            this.imgUrl.url = file.url;
            this.dialogVisible = true;
        },

        inputReturn() {
            let flag = true
            if (this.limit == 1 && this.isMust && this.fileList.length == 0 && this.AllFile.length == 0) {
                this.isHit = true
                flag = false
            }
            return flag
        },

        //文件状态改变时的函数(主要逻辑函数)
        uploadFile(e, fileList) {

            this.AllFile = JSON.parse(JSON.stringify(fileList))
            //判断用户上传最大数量限制,来让上传按钮消失
            if (fileList.length >= this.limit) this.showUpload = true;
            // const file = e.file; <- 这里是不需要直接上传而是通过按钮上传的
            const file = e.raw; // <- 这里是直接上传的
            //大小
            const size = file.size / 1024 / 1024 / 2;
            if (
                !(
                    file.type === "image/png" ||
                    file.type === "image/jpg" ||
                    file.type === "image/jpeg"
                )
            ) {
                ElMessage.error({
                    showClose: true,
                    message: this.$t('text.Common.l69'),
                    type: 'error',
                })
                this.$refs.upload.handleRemove(file)
            } else if (size > 5) {
                ElMessage.error({
                    showClose: true,
                    message: this.$t('text.Common.l70'),
                    type: 'error',
                })
                this.$refs.upload.handleRemove(file)
            } else {
                if (this.limit == 1) this.imgUrl = []; //此处判断为一张的时候需要清空数组
                let params = new FormData();
                params.append("file", file);

                axios({
                    url: config.api[0].apiUrl + "/opsli-boot/api/v1/house/file/upload",
                    method: 'post',
                    data: params,
                    headers: { 'T-Authorization': localStorage.getItem('token'), 'Accept-Language': localStorage.getItem("language") == null ? 'zh-CN' : localStorage.getItem("language") == 'zh' ? 'zh-CN' : 'en-US' },
                    processData: false,
                    contentType: false,
                }).then((response) => {
                    if (response.data.code === 0) {
                        this.$emit("returnData", response.data.data.fileUrls);
                    } else {
                        this.$refs.upload.handleRemove(file)
                        ElMessage.error({
                            showClose: true,
                            message: response.data.msg,
                            type: 'error',
                        })
                    }
                }).catch((error) => {
                    this.$refs.upload.handleRemove(file)
                    console.log(error)
                })

            }
        },
        //文件超出个数限制时的函数
        handleExceed(files, fileList) {
            console.log(files, fileList)
            ElMessage.error({
                showClose: true,
                message: `最多只允许上传${this.limit}张图片`,
                type: 'error',
            })
        },
    },
};
</script>

<style  scope>
.hide .el-upload--picture-card {
    display: none !important;
}

.imm {
    display: flex;
}

.imm>.avatar-uploader>.el-upload {
    width: 150px;
    height: 120px;
    line-height: 150px;
    border-radius: 0px;
    background: #fff;
    border: 1px dashed #ccc;
}

.imm>.avatar-uploader>.el-upload-list>.el-upload--picture-card {
    width: 150px;
    height: 120px;
    border-radius: 5px;
}

.imm>.avatar-uploader>.el-upload>i {
    font-size: 28px;
    color: #ccc;
}

.imm>.avatar-uploader>.el-upload-list {
    display: flex;
}

.imm>.avatar-uploader>.el-upload-list>.el-upload-list__item {
    width: 150px;
    height: 120px;
    display: block;
}



.imm>.avatar-uploader>.el-upload-list>.el-upload-list__item>img {
    width: 150px;
    height: 120px;
    border-radius: 0px;
}

.p6 {
    border: none;
    color: gray;
    outline: none;
    padding-top: 10px;
    padding-left: 10px;
}
</style>
